package com.niodata.dp.web.security;

import com.niodata.dp.core.security.ServiceSecurityManager;
import com.niodata.dp.core.service.SystemService;
import com.niodata.dp.core.usermgr.DpUsermgrException;
import com.niodata.dp.core.usermgr.model.GroupInfo;
import com.niodata.dp.core.usermgr.model.TokenInfo;
import com.niodata.dp.core.usermgr.model.UserGroup;
import com.niodata.dp.core.usermgr.model.UserInfo;
import com.niodata.dp.core.usermgr.op.GroupInfoService;
import com.niodata.dp.core.usermgr.op.TokenInfoService;
import com.niodata.dp.core.usermgr.op.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("dpUserDetailsService")
public class DpJdbcUserDetailService implements UserDetailsService {

  @Autowired
  @Qualifier("DpUserMgrUser")
  private UserService userOperation;

  @Autowired
  @Qualifier("DpUserMgrGroup")
  private GroupInfoService groupOperation;

  @Autowired
  @Qualifier("ServiceSecurityManagerImpl")
  private ServiceSecurityManager serviceSecurityManager;

  @Autowired
  @Qualifier("tokenInfoServiceImpl")
  private TokenInfoService tokenInfoService;



  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserInfo userInfo = null;
    try {
      userInfo = userOperation.getUserInfo(username);
      if (userInfo == null) {
        throw new UsernameNotFoundException(username);
      }
      List<UserGroup> groupList = groupOperation.getUserGroups(userInfo.getUserId());
      List<GroupInfo> groupInfoList = groupOperation.getAllGroups(groupList);
      List<SystemService> serviceInfos = serviceSecurityManager
            .getUserGrantedServices(userInfo.getUserId());
      return new DpUserDetails(userInfo, groupList, groupInfoList, serviceInfos);
    } catch (DpUsermgrException e) {
      e.printStackTrace();
      throw new UsernameNotFoundException(username);
    }
  }

  public UserDetails loadUserByToken(String token) {
    TokenInfo tokenInfo = tokenInfoService.getToken(token);
    UserInfo userInfo = userOperation.getUserInfo(tokenInfo.getUserId());
    if (userInfo == null) {
      throw new UsernameNotFoundException(token);
    }
    List<UserGroup> groupList = groupOperation.getUserGroups(userInfo.getUserId());
    List<GroupInfo> groupInfoList = groupOperation.getAllGroups(groupList);
    List<SystemService> serviceInfos = serviceSecurityManager
          .getUserGrantedServices(userInfo.getUserId());
    return new DpUserDetails(userInfo, groupList, groupInfoList, serviceInfos);
  }

}
